package com.yunshipei.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yunshipei.EnterApplication;
import com.yunshipei.adapter.SortAdapter;
import com.yunshipei.common.PinyinComparator;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.base.BaseSubscriberAdapter;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.UserInfo;
import com.yunshipei.enterplorer.R;
import com.yunshipei.inter.ContactsRefreshCallBack;
import com.yunshipei.model.FrequentContacts;
import com.yunshipei.model.GroupInfoTab;
import com.yunshipei.model.GroupTabAndContact;
import com.yunshipei.model.SortModel;
import com.yunshipei.model.YspEvent.UserAvatarChangedEvent;
import com.yunshipei.model.YspEvent;
import com.yunshipei.ui.activity.DetailContactsActivity;
import com.yunshipei.ui.activity.GroupListActivity;
import com.yunshipei.ui.view.SideBar;
import com.yunshipei.ui.view.SideBar.OnTouchingLetterChangedListener;
import com.yunshipei.utils.CharacterParser;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.app.model.UserInfoByUserId;
import io.rong.eventbus.EventBus;

//import de.greenrobot.event.EventBus;

/**
 * 通信录
 *
 * @author cike
 */
@SuppressLint("ValidFragment")
public class ContactsToFragment extends Fragment implements CustomerInfoFragment.AvatarUpdateInterface {

    private ListView sortListView;
    private SortAdapter adapter;
    private GroupTabAndContact groupTabAndContact;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    private ContactsRefreshCallBack callBack;


    public static ContactsToFragment newInstances() {
        return new ContactsToFragment();
    }

    @Override
    public void onCreate(Bundle a) {
        super.onCreate(a);
        Fragment fragments = getParentFragment();
        fragments.getTag();
        EventBus.getDefault().register(this);
        //发送网络请求
        getUsualUserList();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_listview_sort_main, container, false);
        // 实例化汉字转拼音类
        pinyinComparator = new PinyinComparator();
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (v.getId()) {
                    case R.id.sidrbar:
                        Toast.makeText(EnterApplication.getApp(), "contactToFragment", Toast.LENGTH_LONG).show();
                        break;
                    default:
                        Toast.makeText(EnterApplication.getApp(), "1234567890", Toast.LENGTH_LONG).show();
                        break;
                }
                return true;
            }
        });

        SideBar sideBar = (SideBar) view.findViewById(R.id.sidrbar);
        TextView dialog = (TextView) view.findViewById(R.id.dialog);
        sideBar.setTextView(dialog);
        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position - 1);
                }

            }
        });
        sortListView = (ListView) view.findViewById(R.id.country_lvcountry);
        sortListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent();
                if (position != 0) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("userInfo", groupTabAndContact.getmSortList().get(position - 1).getUserInfo());
                    intent.putExtras(bundle);
                    intent.setClass(getActivity(), DetailContactsActivity.class);
                    startActivity(intent);
                } else {
                    if (YspPreferences.getInstance().getSharedPreferences().getBoolean("RCSconnectStatus", false)) {
                        intent.setClass(getActivity(), GroupListActivity.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(getActivity(), "IM功能不可用", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        // 网络请求回来的数据再有他处理一下
        /*
      汉字转换成拼音的类
     */
        List<SortModel> sourceDateList = new ArrayList<SortModel>();
        // 设置我的群组名称
        GroupInfoTab groupInfoTab = new GroupInfoTab("", getActivity().getResources().getString(R.string.de_actionbar_sub_group));
        groupTabAndContact = new GroupTabAndContact();
        groupTabAndContact.setmSortList(sourceDateList);
        groupTabAndContact.setGroupTab(groupInfoTab);
        new FrequentContacts();

        // 根据a-z进行排序源数据
        Collections.sort(groupTabAndContact.getmSortList(), pinyinComparator);

        if (adapter == null) {
            adapter = new SortAdapter(getActivity(), groupTabAndContact);
            sortListView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }

        return view;
    }

    /**
     * 为ListView填充数据
     */
    private List<SortModel> filledData(FrequentContacts frequentContacts) {
        List<SortModel> mSortList = new ArrayList<SortModel>();
        // 网络获取的通信录的列表信息
        int length = frequentContacts.getData().getMembers().size();
        for (int i = 0; i < length; i++) {
            SortModel sortModel = new SortModel();
            //
            sortModel.setUserInfo(frequentContacts.getData().getMembers()
                    .get(i));
            // 汉字转换成拼音
            String pinyin = CharacterParser.getInstance().getSelling(frequentContacts
                    .getData().getMembers().get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        if (callBack != null) {
            sortListView.setTag(0);
            callBack.setChildFragmentListView(sortListView);
        }
    }

    public void getUsualUserList() {
        SharedPreferences mySharedPreferences = YspPreferences.getInstance().getSharedPreferences();
        String departId = mySharedPreferences.getString("departmentId", mySharedPreferences.getString("topId", ""));
        String companyId = mySharedPreferences.getString("companyId", "");
        String uuid = mySharedPreferences.getString("uuid", "");
        HttpMethods.getInstance().getColleagues(companyId, uuid, departId, new ContactsToSubscriber());
    }

    private class ContactsToSubscriber extends BaseSubscriberAdapter<FrequentContacts> {
        @Override
        public void onNext(FrequentContacts frequentContact) {
            //网络请求回来的数据再有他处理一下
            groupTabAndContact.setmSortList(filledData(frequentContact));
            // 根据a-z进行排序源数据
            Collections.sort(groupTabAndContact.getmSortList(), pinyinComparator);
            adapter.updateListView(groupTabAndContact);
            List<UserInfo> members = frequentContact.getData().getMembers();
            int size = members.size();
            Map<String, io.rong.imlib.model.UserInfo> map = new HashMap<String, io.rong.imlib.model.UserInfo>();
            for (int i = 0; i < size; i++) {
                io.rong.imlib.model.UserInfo user = new io.rong.imlib.model.UserInfo(members.get(i).getUuid(), members.get(i).getName(), null);
                map.put(members.get(i).getUuid(), user);
            }
            UserInfoByUserId.getInstance().insertUserInfo(map);
            if (callBack != null) {
                callBack.setContactsToRefreshFinished(true);
            }
        }

        @Override
        public void onError(String errorMessage) {
            if (callBack != null) {
                callBack.setContactsToRefreshFinished(true);
            }
        }
    }

    @Override
    public void avatarUpdateEvent(String uuid, String uriStr) {
        if (groupTabAndContact.getmSortList() != null) {
            for (int i = 0; i < groupTabAndContact.getmSortList().size(); i++) {
                if (groupTabAndContact.getmSortList().get(i).getUserInfo().getUuid().equals(uuid)) {
                    groupTabAndContact.getmSortList().get(i).getUserInfo().setAvatar(uriStr);
                    break;
                }
            }
            adapter.updateListView(groupTabAndContact);
        }
    }

    public void onEventMainThread(UserAvatarChangedEvent event) {
        avatarUpdateEvent(event.getUuid(), event.getData());
    }

    public void onEventMainThread(YspEvent.RefreshCommonContact commonContact) {
        getUsualUserList();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void setRefreshCallBack(ContactsRefreshCallBack callBack) {
        this.callBack = callBack;
    }
}
